﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Specialized; 

namespace WeChatDataSrc
{
   public  class HttpPost
    {
       /// <summary>
       /// 发送文本数据
       /// </summary>
       /// <param name="url"></param>
       /// <param name="postData">待发送的数据</param>
       /// <returns></returns>
       public static string SendData(string url, string postData)
       {
           //Console.WriteLine("================{0} Post Data=============", DateTime.Now.ToString());
           //Console.WriteLine(url);
           //Console.WriteLine(postData);
           //Console.WriteLine("================================================");
           ASCIIEncoding encoding = new ASCIIEncoding();
           HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
           HttpWebResponse response = null;
           String returnStr;//服务器端返回的消息 

           byte[] data = System.Text.Encoding.UTF8.GetBytes(postData);

           request.Method = "POST";
           request.ContentType = "application/x-www-form-urlencoded";
           request.ContentLength = data.Length;
           try
           {
               Stream stream = request.GetRequestStream();
               // Send the data.
               stream.Write(data, 0, data.Length);
               stream.Close();
               response = (HttpWebResponse)request.GetResponse();
               StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.Default);
               returnStr = streamReader.ReadToEnd();// reader.ReadToEnd();
           }
           catch (System.Net.WebException e)
           {
               throw new Exception("指定的网络服务不可用!");
           }

           return returnStr;
       }
      
       /// <summary>
       /// 上传文件
       /// </summary>
       /// <param name="url"></param>
       /// <param name="fileName">待上传的文件路径</param>
       /// <returns></returns>
       public static string UploadFile(string url, string fileName)
       {
           FileInfo fi = new FileInfo(fileName);

           //服务器端返回的消息 
           String returnStr;

           // 要上传的文件 
           FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
           BinaryReader binaryReader = new BinaryReader(fileStream);

           //时间戳 
           string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
           byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");

           //请求头部信息 
           StringBuilder sb = new StringBuilder();
           sb.Append("--");
           sb.Append(strBoundary);
           sb.Append("\r\n");
           sb.Append("Content-Disposition: form-data; name=\"");
           sb.Append("file");
           sb.Append("\"; filename=\"");
           sb.Append(fi.Name);
           sb.Append("\"");
           sb.Append("\r\n");
           sb.Append("Content-Type: ");
           sb.Append("application/octet-stream");
           sb.Append("\r\n");
           sb.Append("\r\n");
           string strPostHeader = sb.ToString();
           byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);

           // 根据uri创建HttpWebRequest对象 
           HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
           httpReq.Method = "POST";

           //对发送的数据不使用缓存 
           httpReq.AllowWriteStreamBuffering = false;

           //设置获得响应的超时时间（300秒） 
           httpReq.Timeout = 300000;
           httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
           long length = fileStream.Length + postHeaderBytes.Length + boundaryBytes.Length;
           long fileLength = fileStream.Length;
           httpReq.ContentLength = length;
           try
           {
               //每次上传4k 
               int bufferLength = 4096;
               byte[] buffer = new byte[bufferLength];

               //已上传的字节数 
               long offset = 0;

               //开始上传时间 
               DateTime startTime = DateTime.Now;
               int size = binaryReader.Read(buffer, 0, bufferLength);
               Stream postStream = httpReq.GetRequestStream();

               //发送请求头部消息 
               postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
               while (size > 0)
               {
                   postStream.Write(buffer, 0, size);
                   offset += size;
                 
                   TimeSpan span = DateTime.Now - startTime;
                   double second = span.TotalSeconds;

                   size = binaryReader.Read(buffer, 0, bufferLength);
               }
               //添加尾部的时间戳 
               postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
               postStream.Close();

               //获取服务器端的响应 
               WebResponse webRespon = httpReq.GetResponse();
               Stream stream = webRespon.GetResponseStream();
               StreamReader streamReader = new StreamReader(stream);

               //读取服务器端返回的消息 
               returnStr = streamReader.ReadLine();
               stream.Close();
               streamReader.Close();
               
           }
           catch(Exception ex)
           {
               throw ex;
           }
           finally
           {
               fileStream.Close();
               binaryReader.Close();
           }

           return returnStr;
       }

    }
}
